package com.quick.common.utils.ip;

import com.alibaba.fastjson2.JSONObject;
import com.quick.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


/**
 * 地址解析
 *
 * @Author: Administrator
 * @Date: 2023/7/17
 */
@Slf4j
public class AddressUtils {
    public static final String IP_URL = "https://whois.pconline.com.cn/ipJson.jsp";
    public static final String UN_KNOWN = "未知";
    public static final String INTRANET = "内网IP";

    public static String getRealAddressByIp(String ip) {
        if (IpUtils.internalIp(ip)) {
            return INTRANET;
        }
        try {
            String rspStr = HttpUtils.sendGet(IP_URL + "?ip=" + ip + "&json=true");
            if (StringUtils.isEmpty(rspStr)) {
                return UN_KNOWN;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            String addr = obj.getString("addr");
            return StringUtils.isEmpty(addr) ? String.format("%s %s", region, city) : addr;
        } catch (Exception e) {
            log.error("{}.", e.getMessage(), e);
        }
        return UN_KNOWN;
    }

}
